from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import NoSuchElementException
import sys
import time
def shared_lessons(driver):
    items=[]
    sharing_class = driver.find_element(By.ID, 'sharingClassed')
    datalist = sharing_class.find_elements(By.CLASS_NAME, 'datalist')
    for one in datalist:
        name=one.find_element(By.CLASS_NAME, 'courseName')
        test=one.find_elements(By.CLASS_NAME, 'course-menu-w')[1]
        items.append([name,test])
    return items

def before_read(driver):
    time.sleep(3600)
    try:
        WebDriverWait(driver, 15).until( EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div/div[6]/div[2]/div[1]/i')) )
    except TimeoutException:
        print('超时15s, 未找到元素 in before_read...')
        sys.exit(1)

    # parent = driver.find_element(By.XPATH, '//*[@id="app"]/div/div[6]/div[2]')
    return driver.find_element(By.XPATH, '//*[@id="app"]/div/div[6]/div[2]/div[1]/i')

def ai_assitant(driver):
    try:
        WebDriverWait(driver, 15).until( EC.presence_of_element_located((By.XPATH, '//*[@id="outContainer"]/div[1]/div/div[1]/div[1]/img[1]')) and EC.presence_of_element_located((By.XPATH, '//*[@id="outContainer"]/div[1]/div/div[1]/div[1]/img[2]')) )
    except TimeoutException:
        print('超时15s, 未找到元素 in ai_assitant...')
        sys.exit(1)
    ai = driver.find_element(By.XPATH, '//*[@id="outContainer"]/div[1]/div/div[1]/div[1]/img[1]')
    close = driver.find_element(By.XPATH, '//*[@id="outContainer"]/div[1]/div/div[1]/div[1]/img[2]')
    return [ai, close]

def video_area(driver):
    try:
        WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, 'videoArea')))
    except TimeoutException:
        print('超时10s, 未找到元素 in video_area...')
        sys.exit(1)
    
    return driver.find_element(By.CLASS_NAME, 'videoArea')

def play_video(driver):
    videoarea = video_area(driver)
    action = ActionChains(driver)
    action.move_to_element_with_offset(videoarea, 100, 100).click(videoarea).perform()

    # if EC.presence_of_element_located((By.CSS_SELECTOR, '#playButton.playButton')):
    #     play_button = video_area.find_element(By.CSS_SELECTOR, '#playButton.playButton')
    #     play_button.click()

def current_time(driver):
    try:
        WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, '//*[@id="vjs_container"]/div[10]/div[4]/span[1]')) )
    except TimeoutException:
        print('超时10s, 未找到元素 in current_time...')
        sys.exit(1)
    
    videoarea = video_area(driver)
    action = ActionChains(driver)
    action.move_to_element_with_offset(videoarea, 100, 100).perform()
    # 等待出现
    time.sleep(1)
    return driver.find_element(By.XPATH, '//*[@id="vjs_container"]/div[10]/div[4]/span[1]')

def video_list(driver):
    try:
        WebDriverWait(driver, 15).until( EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[1]/div')))
    except TimeoutException:
        print('超时15s, 未找到元素 in video_list...')
        sys.exit(1)
    chapter_root = driver.find_element(By.XPATH, '//*[@id="app"]/div/div[2]/div[2]/div[2]/div[1]/div')
    chapters = chapter_root.find_elements(By.CLASS_NAME, 'list')
    video_items = []
    for chapter in chapters:
        for one in chapter.find_elements(By.CSS_SELECTOR, '.clearfix.video'):
            video_items.append(one)
    
    return video_items

def interrupt_test(driver):
    try:
        WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.XPATH, '//*[@id="playTopic-dialog"]/div')))
    except TimeoutException:
        print('[正常] 延时5s, 暂未出现元素 in interrupt_test...')
        return 
    # 当没有异常说明有中断测试，需要选择再关闭它
    print('出现中断测试题...')
    test_root = driver.find_element(By.XPATH, '//*[@id="playTopic-dialog"]/div')
    test_type = test_root.find_element(By.CLASS_NAME, 'title-tit')
    choice_texts = ''
    if '判断题' in test_type.text or '单选题' in test_type.text:
        first_choice = test_root.find_element(By.CLASS_NAME, 'topic-item')
        choice_text = first_choice.find_element(By.CLASS_NAME, 'item-topic')
        choice_texts = choice_texts + '\n' + choice_text.text
        # 如果之前选中了就直接关闭
        try:
            test_root.find_element(By.CLASS_NAME, 'answer')
        except NoSuchElementException:
            # 选中
            first_choice.click()
        close = test_root.find_element(By.CLASS_NAME, 'el-dialog__footer')
        # 关闭
        close.click()
        # 播放
        play_video(driver)
        print(f'已自动选择选项: {choice_texts} ')
    elif '多选题' in test_type.text:
        choices = test_root.find_elements(By.CLASS_NAME, 'topic-item')
        for choice in choices:
            choice_text = choice.find_element(By.CLASS_NAME, 'item-topic')
            choice_texts = choice_texts +'\n'+ choice_text.text
            try:
                test_root.find_element(By.CLASS_NAME, 'answer')
            except NoSuchElementException:
                choice.click()
            
        close = test_root.find_element(By.CLASS_NAME, 'el-dialog__footer')
        # 关闭
        close.click()
        # 播放
        play_video(driver)
        print(f'已自动选择选项: {choice_texts} ')

def accelerate_video(driver):
    print('[Debug] 即将悬浮到videoarea 5s...')
    time.sleep(5)
    videoarea = video_area(driver)
    action = ActionChains(driver)
    action.move_to_element_with_offset(videoarea, 100, 100).perform()
    try:
        speedBox = WebDriverWait(driver, 2).until(
            EC.visibility_of_element_located((By.CLASS_NAME, 'speedBox'))
        )   
        print(f'[Debug] 即将悬浮到speedbox 0s text: {speedBox.text}...')
        action.move_to_element(speedBox).perform()
        action.click(speedBox).perform()
        try:
            # 使用JavaScript直接查找并修改.speedList的display属性
            driver.execute_script("""
                var speedList = document.querySelector('.able-player-container .able-player-skin .controlsBar .speedBox .speedList');
                if (speedList) {
                    speedList.style.display = 'block';
                }
            """)
        
            print("Speed list is now visible.")
        except Exception as e:
            print(f"An error occurred: {e}")
        try:
            max_speed = WebDriverWait(speedBox, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.speedTab.speedTab15')))
            action.click(max_speed).perform()
        except TimeoutException:
            print('超时5s, 元素不可点击 in accelerate_video...')
            
    except TimeoutException:
        print('超时2s, 未找到元素 in accelerate_video...')
        
    except Exception as e:
        print(f'加速视频时出错: {e}')
        # 可以选择在这里重新尝试或记录错误




def finish_flag(item):
    try:
        WebDriverWait(item, 5).until( EC.presence_of_element_located((By.CSS_SELECTOR, '.fl.time_icofinish')))
    except TimeoutException:
        print('[正常] 延时5s, 暂未出现元素 in finish_flag...')
        return False
    first_div = item.find_element(By.TAG_NAME, 'div')
    first_span = first_div.find_element(By.TAG_NAME, 'span')
    print(f'[Debug] {first_span.text}结束')
    return True

__all__  = ["shared_lessons", "before_read", "ai_assitant", 'video_list', 'interrupt_test', 'finish_flag', 'play_video', 'video_area', 'current_time', 'accelerate_video']